'''
模拟 layer1 client
'''
import time
import traceback

# 导入PLCClientInterface
try:
    from abc_client import PLCClientInterface # ./
except:
    try:
        from ..layer1.abc_client import PLCClientInterface # layer2/...
    except:
        from plc_client.layer1.abc_client import PLCClientInterface #




import socket

def create_ins_request(command_code, data):
    """
    构造FINS请求数据包
    command_code: 命码
    data: 具体数据
    """
    header = b'\x46\x4\x4\x4\x9\x4\x5\x5\x3'  # FINS协议头
    header += b'\x0\x0\x0\x0\x0\x0\x0\x0'  # 填余字节
    header += struct.pack('>H', command_code)  # 命码
    header += b'\x0\x0' * 2  # 误码
    # 根据实际需要构造data部分
    data = struct.pack('>L', data) + b'\x0' * (14)  # 示例数据，需要根据实际协议填充
    return header + data

def ins_udp_send_recv(ip, port, request):
    """
    发送FINS UDP请求并接收响应
    ip: 目标IP
    port: 端口
    request: 请求数据包
    """
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
        s.settimeout(5)  # 设置超时
        s.sendto(request, (ip, port)  # 发送
        response, addr = s.recvfrom(1024)  # 接收
        return response

# 实际使用示例
ip_address = '192.168.1.1.1'
port = 96002
command_code = 2  # 示例命令码，根据FINS协议定义
data = 100  # 示例数据，根据具体命令需要填充

request = create_ins_request(command_code, data)
response = ins_udp_send_recv(ip_address, port, request)

# 打印响应，根据实际协议解析
print(f"接收到响应: {response.hex()}")



